package com.yunshu.yunshuapp.kuaixun;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.constant.WBConstants;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.openapi.BaseReq;
import com.tencent.mm.sdk.openapi.BaseResp;
import com.tencent.mm.sdk.openapi.ConstantsAPI;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.yunshu.yunshuapp.NavigationBar;
import com.yunshu.yunshuapp.R;
import com.yunshu.yunshuapp.network.YSCallback;
import com.yunshu.yunshuapp.network.YSRequest;
import com.yunshu.yunshuapp.utils.YSUtils;
import com.yunshu.yunshuapp.views.CommonLoadingView;

import java.io.IOException;
import java.util.ArrayList;

public class KuaixundetailActivity extends AppCompatActivity implements View.OnClickListener , IWXAPIEventHandler , IWeiboHandler.Response , IUiListener {

    private KuaixunListModel model;

    private TextView timeTV;
    private TextView contentTV;

    private IWXAPI api;
    private IWeiboShareAPI mWeiboShareAPI;
    private Tencent mTencent;
    private Boolean qqSharing = false;
    private CommonLoadingView loadingView;
    private ImageButton loveBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kuaixundetail);
        timeTV = (TextView) findViewById(R.id.timeTV);
        contentTV = (TextView) findViewById(R.id.contentTV);
        loadingView = (CommonLoadingView) findViewById(R.id.loadingView);

        NavigationBar bar = (NavigationBar) findViewById(R.id.navigationBar);
        bar.putInActivity(this);
        bar.setTitle("快讯详情");

        Bundle bundle = this.getIntent().getExtras();

        String kxid = (String) bundle.get("kxid");

        this.request(kxid);

        api = WXAPIFactory.createWXAPI(this, YSUtils.WXAPPID, false);
        api.registerApp(YSUtils.WXAPPID);
        api.handleIntent(getIntent(), this);
        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this, YSUtils.WEIBOAPPID);
        mWeiboShareAPI.registerApp();

        mTencent = Tencent.createInstance(YSUtils.QQAPPID, this.getApplicationContext());

        this.addListener();
    }

    private void addListener() {
        ImageButton shareTimelineBtn = (ImageButton) findViewById(R.id.timelineBtn);
        shareTimelineBtn.setOnClickListener(this);

        ImageButton btn2 = (ImageButton) findViewById(R.id.weiboBtn);
        btn2.setOnClickListener(this);

        ImageButton btn3 = (ImageButton) findViewById(R.id.wechatBtn);
        btn3.setOnClickListener(this);

        ImageButton btn4 = (ImageButton) findViewById(R.id.qqBtn);
        btn4.setOnClickListener(this);

        ImageButton btn5 = (ImageButton) findViewById(R.id.qzoneBtn);
        btn5.setOnClickListener(this);

        loveBtn = (ImageButton) findViewById(R.id.loveBtn);
        loveBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.timelineBtn){
            this.share2WX(SendMessageToWX.Req.WXSceneTimeline);

        }else if(view.getId() == R.id.weiboBtn){
            this.share2Weibo();
        }else if(view.getId() == R.id.wechatBtn){
            this.share2WX(SendMessageToWX.Req.WXSceneSession);
        }else if(view.getId() == R.id.qqBtn){
            this.share2QQ();
        }else if(view.getId() == R.id.qzoneBtn){
            this.share2QZone();
        }else if(view.getId() == R.id.loveBtn){
            this.loveZixun();
        }
    }

    private void share2Weibo() {
        if (mWeiboShareAPI.isWeiboAppInstalled()) {

            final WeiboMultiMessage weiboMessage = new WeiboMultiMessage();//初始化微博的分享消息

            TextObject textObject = new TextObject();
            textObject.text = model.getTitle();
            weiboMessage.textObject = textObject;
            loadingView.setVisibility(View.VISIBLE);
            loadingView.load();

            WebpageObject mediaObject = new WebpageObject();
            mediaObject.identify = YSUtils.generateGUID();
            mediaObject.title = model.getTitle();
            mediaObject.description = model.getTitle();
            // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
            mediaObject.setThumbImage(bitmap);
            mediaObject.actionUrl = shareURL();
            mediaObject.defaultText = "云数智惠";
            weiboMessage.mediaObject = mediaObject;
            SendMultiMessageToWeiboRequest request1 = new SendMultiMessageToWeiboRequest();
            request1.transaction = String.valueOf(System.currentTimeMillis());
            request1.multiMessage = weiboMessage;
            qqSharing = false;
            boolean b = mWeiboShareAPI.sendRequest(this,request1);//发送请求消息到微博，唤起微博分享界面

        } else {
            Toast.makeText(this, "没有安装新浪微博客户端", Toast.LENGTH_LONG).show();
        }
    }

    private void share2QQ() {
//        if (!mTencent.is()){
//            Toast.makeText(this, "未安装QQ!", Toast.LENGTH_LONG).show();
//        }
        Bundle bundle = new Bundle();
        //这条分享消息被好友点击后的跳转URL。
        bundle.putString(QQShare.SHARE_TO_QQ_TARGET_URL, this.shareURL());
        //分享的标题。注：PARAM_TITLE、PARAM_IMAGE_URL、PARAM_SUMMARY不能全为空，最少必须有一个是有值的。
        bundle.putString(QQShare.SHARE_TO_QQ_TITLE, model.getTitle());


        //分享的图片URL
        bundle.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, logoURL());
        //分享的消息摘要，最长50个字
//        bundle.putString(QQShare.PARAM_SUMMARY, "测试");

        bundle.putString(QQShare.SHARE_TO_QQ_APP_NAME, "云数智惠");
        //标识该消息的来源应用，值为应用名称+AppId。
//        bundle.putString(QQShare.PARAM_APP_SOURCE, "星期几" + YSUtils.QQAPPID);
        bundle.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);

        qqSharing = true;
        mTencent.shareToQQ(this, bundle , this);
    }

    public void share2QZone(){
        final Bundle params = new Bundle();
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);//类型
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, this.model.getTitle());//标题
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, this.model.getTitle());//概要
        params.putString(QzoneShare.SHARE_TO_QQ_APP_NAME, "云数智惠");
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, this.shareURL());
        ArrayList<String> imageUrls = new ArrayList<String>();
        imageUrls.add("http://www.yunshutech.com/pictureService/showImage.action?type=0&filename=ccbe074f-b85f-454b-bc25-b1f977046222.png");
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUrls);

        mTencent.shareToQzone(KuaixundetailActivity.this, params, KuaixundetailActivity.this);
    }

    private void share2WX(final int WXScene) {
        if (!api.isWXAppInstalled()){
            Toast.makeText(this, "未安装微信!", Toast.LENGTH_LONG).show();
        }

        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = this.shareURL();

        final WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = model.getTitle();
        msg.description = model.getDate();

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

        msg.setThumbImage(bitmap);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
//                    req.transaction = ""
        req.message = msg;
        req.scene = WXScene;
        boolean ret = api.sendReq(req);

    }

    private String shareURL() {
        return YSRequest.BASE_URL + YSRequest.Kuaixun_Share + "id="+this.model.getModelId()+"&iscome=1";
    }

    private  String logoURL(){
        return "http://www.yunshutech.com/pictureService/showImage.action?type=0&filename=ccbe074f-b85f-454b-bc25-b1f977046222.png";
    }

    @Override
    public void onReq(BaseReq req) {
        switch (req.getType()) {
            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
                System.out.println("COMMAND_GETMESSAGE_FROM_WX");
                break;
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
//                goToShowMsg((ShowMessageFromWX.Req) req);
                System.out.println("COMMAND_SHOWMESSAGE_FROM_WX");

                break;
            default:
                break;
        }
    }

    @Override
    public void onResp(BaseResp resp) {
        int result = 0;

        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                Toast.makeText(this, "成功分享到微信", Toast.LENGTH_LONG).show();

                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                Toast.makeText(this, "取消分享到微信", Toast.LENGTH_LONG).show();

                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                Toast.makeText(this, "分享到微信失败", Toast.LENGTH_LONG).show();

                break;
            default:
                Toast.makeText(this, "分享到微信失败", Toast.LENGTH_LONG).show();

                break;
        }

        Toast.makeText(this, result, Toast.LENGTH_LONG).show();
    }

    public void request(String kxid){
        YSRequest request = new YSRequest(this);
        kxid = kxid.replace("\"","");
        request.GET(YSRequest.Kuaixun_Detail,"&id="+ Long.parseLong(kxid), new YSCallback() {

            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                if (isSuccess != YSRequest.REQUEST_OK) return;
                ObjectMapper mapper = new ObjectMapper();
                String jsonstr = result.toString();
                try {
                    model = mapper.readValue(jsonstr, KuaixunListModel.class);
                    reloadUI();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mWeiboShareAPI.handleWeiboResponse(intent, this); //当前应用唤起微博分享后，返回当前应用
    }

    public void onResponse(BaseResponse baseResp) {//接收微客户端博请求的数据。

        switch (baseResp.errCode) {
            case WBConstants.ErrorCode.ERR_OK:
                Toast.makeText(this, "成功分享到微博", Toast.LENGTH_LONG).show();
                break;
            case WBConstants.ErrorCode.ERR_CANCEL:
                Toast.makeText(this, "取消分享到微博", Toast.LENGTH_LONG).show();
                break;
            case WBConstants.ErrorCode.ERR_FAIL:
                Toast.makeText(this, "分享到微博失败", Toast.LENGTH_LONG).show();
                break;
        }

    }

    @Override
    public void onComplete(Object o) {
        Toast.makeText(this, "成功分享到QQ", Toast.LENGTH_LONG).show();
    }
    public void onError(UiError e) {

        Toast.makeText(this, "分享到QQ失败", Toast.LENGTH_LONG).show();
    }
    public void onCancel() {

        Toast.makeText(this, "取消分享到QQ", Toast.LENGTH_LONG).show();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode,resultCode,data);
        loadingView.setVisibility(View.INVISIBLE);
        if (null != mTencent && qqSharing)
            mTencent.onActivityResultData(requestCode, resultCode, data , this);
    }

    public void reloadUI(){
        runOnUiThread(new Runnable() {      // UI thread
            @Override
            public void run() {
                timeTV.setText(model.getDate());
                contentTV.setText("\u3000\u3000" + model.getTitle());
                updateLoveButton();
            }
        });
    }

    private void showAlert(String kxid) {
        new AlertDialog.Builder(this).setTitle("提示")//设置对话框标题

                .setMessage(kxid)//设置显示的内容 ;
                .setPositiveButton("ok",new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件

                    }
                })
                .show();//在按键响应事件中显示此对话框
    }

    private void loveZixun(){
        final int type = this.model.isLoved(this)? 2:1 ; //点赞
        loadingView.setVisibility(View.VISIBLE);
        new YSRequest(this).GET(YSRequest.KUAIXUN_Love,"id="+this.model.getModelId()+"&type="+type,new YSCallback(){

            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loadingView.setVisibility(View.INVISIBLE);
                    }
                });
                if(isSuccess == YSRequest.REQUEST_OK){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            loadingView.setVisibility(View.INVISIBLE);
                            if (type == 1) {
                                model.setLoved(true,KuaixundetailActivity.this);
                                loveBtn.setBackgroundResource(R.mipmap.zixun_love1);
                            }else{
                                model.setLoved(false,KuaixundetailActivity.this);
                                loveBtn.setBackgroundResource(R.mipmap.zixun_love);

                            }
                        }
                    });
                }else{
                    YSUtils.showToastOn(KuaixundetailActivity.this,"点赞失败，请稍后重试");
                }
            }
        });
    }

    private void updateLoveButton() {
        if(this.model.isLoved(this)) {//点赞
            loveBtn.setBackgroundResource(R.mipmap.zixun_love1);
        }
    }
}
